<?php

namespace app\master\controller;

use app\model\MasterModel;
use app\server\Redis;
use think\App;
use app\common\Base;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Validate;

class Login extends Base {

    /**
     * 登录
     */
    public function doLogin() {
        $postData = $this->request->post();
        $validate = Validate::rule([
            "account|用户名" => "require|min:5",
            "password|密码" => "require|min:6"
        ]);
        if (!$validate->check($postData)) {
            return error($validate->getError());
        }
        $user = MasterModel::where(['username' => $postData['account']])->field('uid,nickname,avatar,rid,status,password')->find();
        if (empty($user)) {
            return error('用户错误');
        }
        $user=$user->toArray();
        if ($user['status'] == 0) {
            return error('用户被禁用');
        }
        $checkStatus = checkPassword($postData['password'], intval($user['uid']), $user['password']);
        if ($checkStatus == false) {
            return error('密码错误');
        }
        MasterModel::where(['uid' => $user['uid']])->update(['login_time' => $this->Time]);
        unset($user['password']);
        $this->request->master=$user;
        $token = createjwt($user);
        $redis = new Redis();
        $redis->setToken($user['uid'], $token);
        return success($user['nickname'].'登录成功', ['token' => $token]);
    }

    /**
     * 退出登录
     */
    public function logout() {
        $redis = new Redis();
        $redis->delToken($this->request->master['uid']);
        return success('注销成功');
    }
}
